有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在Android中将编码的base64图像转换为文件对象

我正在尝试使用AndroidImageSlider库,并用我下载的作为base64字符串的图像填充它

该库仅接受URL、R.drawable值和文件对象作为参数

我试图将图像字符串转换为文件对象,以便传递给库函数。到目前为止,我已经能够从base_64解码并转换成字节[]

String imageData;
byte[] imgBytesData = 安卓.util.Base64.decode(imageData, 安卓.util.Base64.DEFAULT);

共 (1) 个答案

  1. # 1 楼答案

    您需要将File对象保存到磁盘,这样才能工作。此方法将imageData字符串保存到磁盘,并返回关联的File对象

    public static File saveImage(final Context context, final String imageData) {
        final byte[] imgBytesData = android.util.Base64.decode(imageData,
                android.util.Base64.DEFAULT);
    
        final File file = File.createTempFile("image", null, context.getCacheDir());
        final FileOutputStream fileOutputStream;
        try {
            fileOutputStream = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    
        final BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(
                fileOutputStream);
        try {
            bufferedOutputStream.write(imgBytesData);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                bufferedOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file;
    }
    

    它会在应用程序的“缓存”目录中创建一个临时文件。但是,一旦不再需要该文件,您仍需负责删除该文件